//
//  UITools.m
//  微信
//
//  Created by huangdl on 15/9/24.
//  Copyright (c) 2015年 黄驿. All rights reserved.
//

#import "TZImagePickerTool.h"
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>
#import <Photos/Photos.h>
#import "TZImageManager.h"
#import <TZImagePickerController.h>

@interface TZImagePickerTool ()<UIActionSheetDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate,TZImagePickerControllerDelegate> {
    UIViewController *_vc;
    BOOL _isEdit;
    BOOL _isCamera;
}
@property (nonatomic,copy) void(^editedCB)(UIImage *origionImg,UIImage *editedImage);
@property (nonatomic,copy) void(^cb)(UIImage *img);



-(void)selectImageFrom:(id)obj complete:(void(^)(UIImage *img))cb isCamera:(BOOL)isCamera;

-(void)selectImageForEditFrom:(id)obj complete:(void(^)(UIImage *origionImg,UIImage *editedImage))cb isCamera:(BOOL)isCamera;

@end


@implementation TZImagePickerTool

+ (BOOL)checkCameraPermission {
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusDenied) {
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"请打开相机权限" message:@"设置-隐私-相机" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        alertView.tag = 100;
        [alertView show];
        return NO;
    } else{
        return YES;
    }
    return YES;
}
+(BOOL)checkPhotoPermisson {
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
    if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) {
        //无权限
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"请打开相册权限" message:@"设置-隐私-相册" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        alertView.tag = 100;
        [alertView show];
        return NO;
    }else{
        return YES;
    }
    return YES;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0 && alertView.tag == 100) {
        NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if([[UIApplication sharedApplication] canOpenURL:url]) {
            [[UIApplication sharedApplication] openURL:url];
        }
    }
}

+(id)tools {
    static TZImagePickerTool *_t = nil;
    if (!_t) {
        _t = [[TZImagePickerTool alloc]init];
    }
    return _t;
}

-(void)selectImageFrom:(id)obj complete:(void(^)(UIImage *img))cb isCamera:(BOOL)isCamera {
    _vc = obj;
    _cb = cb;
    _isEdit = NO;
    _isCamera = isCamera;
    [self showActionSheetWithIsCamera:isCamera];
}

-(void)selectImageForEditFrom:(id)obj complete:(void(^)(UIImage *origionImg,UIImage *editedImage))cb isCamera:(BOOL)isCamera {
    _vc = obj;
    _editedCB = cb;
    _isEdit = YES;
    [self showActionSheetWithIsCamera:isCamera];
}

- (void)showActionSheetWithIsCamera:(BOOL)isCamera {
    if (isCamera) {
        UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
        PickerImage.sourceType = UIImagePickerControllerSourceTypeCamera;
        PickerImage.allowsEditing = YES;
        PickerImage.delegate = self;
        PickerImage.navigationBar.translucent = NO;
//        UINavigationController * nav = [[UINavigationController alloc]initWithRootViewController:PickerImage];
        [_vc.navigationController presentViewController:PickerImage animated:YES completion:nil];
    }else {
        UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
        PickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        PickerImage.allowsEditing = _isEdit;
        PickerImage.delegate = self;
        PickerImage.navigationBar.translucent = NO;
//        UINavigationController * nav = [[UINavigationController alloc]initWithRootViewController:PickerImage];
        [_vc.navigationController presentViewController:PickerImage animated:YES completion:nil];
    }
}
- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    UINavigationBar *navigationBar = navigationController.navigationBar;
    [navigationBar setBackgroundImage:[CommonTools imageCreateWithColor:[UIColor colorWithHex:0xffffff]] forBarMetrics:UIBarMetricsDefault];
    navigationBar.tintColor = [UIColor blackColor];
    [navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
}
+(void)selectImageFrom:(id)obj complete:(void(^)(UIImage *img))cb isCamera:(BOOL)isCamera{
    [[TZImagePickerTool tools] selectImageFrom:obj complete:cb isCamera:isCamera];
}

+(void)selectImageForEditFrom:(id)obj complete:(void(^)(UIImage *origionImg,UIImage *editedImage))cb isCamera:(BOOL)isCamera {
    [[TZImagePickerTool tools] selectImageForEditFrom:obj complete:cb isCamera:isCamera];
}

#pragma mark --图片选择器的代理
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    image = [self fixOrientation:image];
    UIImage *editImage = info[UIImagePickerControllerEditedImage];
    editImage = [self fixOrientation:editImage];
    
    UIImage *cutDownEditImage = [self imageScale:editImage size:CGSizeMake(800, 800 * editImage.size.height / editImage.size.width)];
    UIImage *cutDownImage = [self imageScale:image size:CGSizeMake(800, 800 * image.size.height / image.size.width)];
    if (_isEdit) {
        _editedCB(cutDownImage,cutDownEditImage);
    } else {
        _cb(cutDownImage);
    }
}

#pragma mark - 私有方法

/**
 *  压缩图片尺寸,方便上传服务器
 */
- (UIImage *)imageScale:(UIImage *)img size:(CGSize)size{
    if (size.width <= img.size.width) {
        return img;
    }
    UIGraphicsBeginImageContext(size);
    // 绘制改变大小的图片
    [img drawInRect:CGRectMake(0,0, size.width, size.height)];
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage =UIGraphicsGetImageFromCurrentImageContext();
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    //返回新的改变大小后的图片
    return scaledImage;
}

- (UIImage *)fixOrientation:(UIImage *)aImage {
    
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
 
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}

#pragma mark -- 视频选择

-(void)selectVideoFor:(id)obj isDismiss:(BOOL)isDismiss complete:(videoBlock)complete {
    _vc = obj;

    TZImagePickerController *imagePicker = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:nil];
    imagePicker.allowPickingOriginalPhoto = NO;
    imagePicker.allowPickingVideo = YES;
    imagePicker.allowPickingImage = NO;
    imagePicker.didFinishPickingVideoHandle = ^(UIImage *coverImage, PHAsset *asset) {
        if (isDismiss) {
            [[UIViewController currentViewController].navigationController dismissViewControllerAnimated:NO completion:nil];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
            options.version = PHImageRequestOptionsVersionCurrent;
            options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
            
            PHImageManager *manager = [PHImageManager defaultManager];
            [manager requestAVAssetForVideo:asset options:options resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
                AVURLAsset *urlAsset = (AVURLAsset *)asset;
                NSURL *videoUrl = urlAsset.URL;
//                LKLog(@"%@",videoUrl.absoluteString);
                
                // 获取音频时长
                AVURLAsset* audioAsset =[AVURLAsset URLAssetWithURL:videoUrl options:nil];
                CMTime audioDuration = audioAsset.duration;
                long duration = CMTimeGetSeconds(audioDuration);
                
                if (complete) {
                    complete(coverImage, videoUrl.absoluteString, duration);
                }
                return;
            }];
        });
    };
    
    [[UIViewController currentViewController].navigationController presentViewController:imagePicker animated:YES completion:nil];
}


@end
